import { deviceManagerControllerGetDeviceModelList } from '@/services/ess/deviceManager';
import { stationSelfDeviceControllerImplAddStationDevice as addDevice } from '@/services/ess/stationDevice';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { Button, Form, Input, message, Modal, Select, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';

interface AddProps {
  handleAddSubmit: (data: any) => void;
  areaId?: string; // 新增
  isArea?: boolean; // 站点是否有分区
  isRoot?: boolean;
  hasArea?: boolean;
  hasDevice?: boolean;
  stationCode?: string;
  queryTreeList: () => void;
}

interface DeviceModelVO {
  deviceId: number;
  deviceModelName: string;
}

interface VoltLevelOption {
  label: string;
  value: string | number;
}

const AddModal: React.FC<AddProps> = ({
  handleAddSubmit,
  areaId,
  isRoot,
  hasArea,
  hasDevice,
  queryTreeList,
}) => {
  // 修改
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [deviceType, setDeviceType] = useState<number | undefined>(undefined);
  const [voltLevels, setVoltLevels] = useState<VoltLevelOption[]>([]);
  const [deviceModelList, setDeviceModelList] = useState<DeviceModelVO[]>([]);
  const [meterTypes, setMeterTypes] = useState<VoltLevelOption[]>([]);
  const intl = useIntl();
  const fetchDeviceModelList = async (deviceType: number) => {
    try {
      const result = await deviceManagerControllerGetDeviceModelList({ deviceType });
      setDeviceModelList(result.data || []);
    } catch (error) {
      console.error(intl.formatMessage({ id: 'siteManage.getDeviceModelFail' }), error);
      setDeviceModelList([]);
    }
  };

  useEffect(() => {
    fetchDictInfo(DATABASE_TYPE_ENUM.VOLT_LEVEL).then((res) => {
      if (res) {
        res.sort((a, b) => {
          // @ts-ignore
          return parseInt(a.value) - parseInt(b.value); // 将字符串转换为整数进行比较
        });
        setVoltLevels(res || []);
      }
    });

    fetchDictInfo(DATABASE_TYPE_ENUM.METER_TYPE).then((res) => {
      if (res) {
        setMeterTypes(res || []);
      }
    });
  }, []);

  const showModal = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const onFinish = async (values: any) => {
    // 查找选中的设备型号的名称并赋值给 model 字段
    const selectedModel = deviceModelList.find((model) => model.deviceId === values.model);
    if (selectedModel) {
      values.model = selectedModel.deviceModelName;
    }

    // 将 areaId 添加到 values 中
    values.areaId = areaId;

    let result = await addDevice({ ...values });
    if (result.success) {
      message.success(intl.formatMessage({ id: 'siteManage.addDeviceSuccess' }));
      handleAddSubmit(result);
      queryTreeList();
      setVisible(false);
      form.resetFields();
    }
  };

  const deviceTypeOptions = [
    { value: 1, label: intl.formatMessage({ id: 'global.batteryCabinet' }) },
    { value: 2, label: intl.formatMessage({ id: 'global.batteryBox' }) },
    { value: 3, label: intl.formatMessage({ id: 'global.pcs' }) },
    { value: 4, label: intl.formatMessage({ id: 'global.meter' }) },
    { value: 5, label: intl.formatMessage({ id: 'global.transformer' }) },
    { value: 6, label: intl.formatMessage({ id: 'global.integratedController' }) },
    { value: 7, label: intl.formatMessage({ id: 'global.cabinetController' }) },
    { value: 8, label: intl.formatMessage({ id: 'global.pcsController' }) },
    { value: 9, label: intl.formatMessage({ id: 'global.inverter' }) },
    { value: 10, label: intl.formatMessage({ id: 'global.chargingPile' }) },
  ];

  const isDisabled = () => {
    // 根节点且有分区，禁用
    if (isRoot && hasArea) return true;
    // 无分区但有设备，禁用
    if (!hasArea && hasDevice) return false;
    // 其他情况下，启用
    return false;
  };
  console.log('hasArea && hasDevice', hasArea, hasDevice);
  return (
    <>
      <Button
        // disabled={isArea}
        disabled={isDisabled()}
        type="primary"
        onClick={showModal}
        size="middle"
        style={{ paddingInline: 15 }}
      >
        {intl.formatMessage({ id: 'siteManage.addDevice' })}
      </Button>
      <Modal
        title={intl.formatMessage({ id: 'siteManage.addDevice' })}
        visible={visible}
        onCancel={handleCancel}
        footer={null}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          onValuesChange={(changedValues) => {
            if (changedValues.type) {
              setDeviceType(changedValues.type);
              fetchDeviceModelList(changedValues.type);
            }
          }}
        >
          <Form.Item
            name="type"
            label={intl.formatMessage({ id: 'siteManage.deviceType' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.selectDeviceType' }),
              },
            ]}
          >
            <Select options={deviceTypeOptions} />
          </Form.Item>
          <Form.Item
            name="name"
            label={intl.formatMessage({ id: 'siteManage.deviceName' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'siteManage.enterDeviceName' }) },
              {
                max: 32,
                message: intl.formatMessage({ id: 'siteManage.deviceN' }),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="model"
            label={intl.formatMessage({ id: 'siteManage.deviceModel' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.selectDeviceModel' }),
              },
            ]}
          >
            <Select
              options={deviceModelList.map((model) => ({
                label: model.deviceModelName,
                value: model.deviceId,
              }))}
            />
          </Form.Item>
          {/* {deviceType === 2 && (
            <Form.Item
              name="code"
              label={intl.formatMessage({ id: 'siteManage.deviceCode' })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({ id: 'siteManage.enterDeviceCode' }),
                },
              ]}
            >
              <Input />
            </Form.Item>
          )} */}
          {deviceType === 4 && (
            <>
              <Form.Item
                name="voltLevel"
                label={intl.formatMessage({ id: 'siteManage.voltageLevel' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.selectVoltage' }),
                  },
                ]}
              >
                <Select options={voltLevels} />
              </Form.Item>
              <Form.Item
                name="meterType"
                label={intl.formatMessage({ id: 'siteManage.meterType' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.selectMeterType' }),
                  },
                ]}
              >
                <Select options={meterTypes} />
              </Form.Item>
            </>
          )}
          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                <Button onClick={handleCancel}>
                  {intl.formatMessage({ id: 'siteManage.cancel' })}
                </Button>
                <Button type="primary" htmlType="submit">
                  {intl.formatMessage({ id: 'siteManage.confirm' })}
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddModal;
